package com.cqc.lite.web;

import com.cqc.lite.domain.Role;
import com.cqc.lite.domain.UserInfo;
import com.cqc.lite.service.RoleService;
import com.cqc.lite.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping("/user/")
public class UserController {

    private final UserService userService;
    private final RoleService roleService;

    @Autowired
    public UserController(UserService userService,RoleService roleService){
        this.userService=userService;
        this.roleService=roleService;
    }


//    @GetMapping("findAll.do")
    @RequestMapping(value = "findAll.do",method = RequestMethod.GET)
    public ModelAndView findAllUser(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("user-list");
        //查询所有的user
        List<UserInfo> userList=userService.findAll();
        mv.addObject("userList",userList);
        return mv;
    }


    @PostMapping("save.do")
    public String save(UserInfo userInfo){
        int i= userService.save(userInfo);
        System.out.println("i="+i);
        return "redirect:/user/findAll.do";
    }

    @GetMapping("findById.do")
    public ModelAndView findById(String id){
        UserInfo user= userService.findById(id);
        ModelAndView mv=new ModelAndView();
        mv.setViewName("user-show");
        //查询所有的user
        mv.addObject("user",user);
        return mv;
    }


    @GetMapping("findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(String id){
        //1查找user
        UserInfo userInfo = userService.findById(id);
        //获取当前用户的role
        List<Role> userRoleList = userInfo.getRoles();
        String userRoleStr="";
        if(!CollectionUtils.isEmpty(userRoleList)){
            StringBuilder sb = new StringBuilder();
            for (Role role : userRoleList) {
                sb.append(role.getRoleName()).append(",");
            }
            userRoleStr=sb.toString();
        }
        //2查找所有的role,jsp遍历roleList,如果登录用户有该权限，就选中
        List<Role> roleList = roleService.findAll();

        ModelAndView mv=new ModelAndView();
        mv.setViewName("user-role-add");
        mv.addObject("user",userInfo);
        mv.addObject("userRoleStr",userRoleStr);
        mv.addObject("roleList",roleList);
        return mv;
    }


    @PostMapping("addRoleToUser.do")
    public String addRoleToUser(@RequestParam("userId") String userId,
                                @RequestParam(name = "ids",required = true)List<String> roleIdList){
        //删除原有的关联的roleId后在新增
        userService.addRoleToUser(userId,roleIdList);
        return "redirect:/user/findAll.do";
    }
}
